package com.fudan.backend.dao;

import com.fudan.backend.handler.IdTypeHandler;
import com.fudan.backend.pojo.Address;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface AddressDao {
    @Results(id = "addressResultMap", value = {
       @Result(column = "address_id", property = "addressId", typeHandler = IdTypeHandler.class),
       @Result(column = "user_id", property = "userId", typeHandler = IdTypeHandler.class)
    })
    @Select("select * from t_address where " +
            "address_id = #{addressId, typeHandler=com.fudan.backend.handler.IdTypeHandler}")
    Address getAddressByAddressId(String addressId);

    /**
     * 获取用户默认收货地址
     * @param userId 用户id
     */
    @ResultMap("addressResultMap")
    @Select("select * from t_address where " +
            "user_id = #{userId, typeHandler=com.fudan.backend.handler.IdTypeHandler} " +
            "and is_default = 1")
    Address getDefaultAddressByUserId(String userId);

    /**
     * 获取用户所有收货地址
     */
    @ResultMap("addressResultMap")
    @Select("select * from t_address where " +
            "user_id = #{userId, typeHandler=com.fudan.backend.handler.IdTypeHandler}")
    List<Address> getAllAddressByUserId(String userId);
    /**
     * 取消用户默认地址
     * 应当与设置默认地址用事务联用保持一致性
     */
    @Update("update t_address set is_default = 0 where " +
            "user_id = #{userId, typeHandler=com.fudan.backend.handler.IdTypeHandler}")
    Integer cancelDefaultAddressByUserId(String userId);

    @Update("update t_address set is_default = 1 where " +
            "address_id = #{addressId, typeHandler=com.fudan.backend.handler.IdTypeHandler}")
    Integer setDefaultAddressByAddressId(String addressId);

    @Insert("insert into t_address values " +
            "(#{addressId, typeHandler=com.fudan.backend.handler.IdTypeHandler}, " +
            "#{userId, typeHandler=com.fudan.backend.handler.IdTypeHandler}, " +
            "#{name}, " +
            "#{phoneNumber}, " +
            "#{province}, " +
            "#{city}, " +
            "#{district}, " +
            "#{detail}, " +
            "#{tag}, " +
            "#{isDefault})")
    Integer addAddress(Address address);

    @Update("update t_address set " +
            "user_id = #{userId, typeHandler=com.fudan.backend.handler.IdTypeHandler}, " +
            "name = #{name}, " +
            "phone_number = #{phoneNumber}, " +
            "province = #{province}, " +
            "city = #{city}, " +
            "district = #{district}, " +
            "detail = #{detail}, " +
            "tag = #{tag} " +
            "where address_id = #{addressId, typeHandler=com.fudan.backend.handler.IdTypeHandler}")
    Integer updateAddress(Address address);

    @Delete("delete from t_address where address_id = #{addressId}")
    Integer deleteAddressByAddressId(String addressId);
}
